package com.ihighest.app.infox.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.core.Application;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.bean.ChannelItem;
import com.ihighest.app.infox.bean.ChannelManage;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.tools.RegexKit;
import com.umeng.message.PushAgent;

public class LoginActivity extends BaseActivity implements OnClickListener {

	final static String TAG = "LoginActivity";

	private ActivityTitle title;
	private Intent intent;
	private JSONArray ids;

	EditText userNameEditText, passwordEditText;
	String userName, password;
	private Handler handler;

	private Button login;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Application.getInstance().addActivity(this);
		setContentView(R.layout.infox_activity_login);

		title = (ActivityTitle) findViewById(R.id.infox_loginActivity_title);
		title.setTitle("登录金草帽");
		title.setViewGone(title.rightLayout, title.titleRefresh, title.titleMsg);
		title.setViewVersible(title.titleBack);
		title.titleBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				login.setClickable(true);
				finish();
			}
		});
		initView();
	}

	private void initView() {

		login = (Button) findViewById(R.id.infox_loginActivity_loginBtn);
		login.setOnClickListener(this);
		findViewById(R.id.infox_loginactivity_frogectPsd).setOnClickListener(this);
		findViewById(R.id.infox_loginActivity_registerBtn).setOnClickListener(this);

		userNameEditText = (EditText) findViewById(R.id.infox_loginActivity_userName);
		passwordEditText = (EditText) findViewById(R.id.infox_loginActivity_userPsd);
		String lastKey = SharedPreferencesKit.getString(this, Const.SP_KEY_LAST_LOGIN_KEY);
		if (!TextUtils.isEmpty(lastKey)) {
			userNameEditText.setText(lastKey);
			passwordEditText.requestFocus();
		}
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				finish();
			}
		};

	}

	@Override
	public void onClick(View view) {

		switch (view.getId()) {
		case R.id.infox_loginActivity_loginBtn:
			login.setClickable(false);

			userName = userNameEditText.getText().toString();
			password = passwordEditText.getText().toString();
			if (TextUtils.isEmpty(userName) || !RegexKit.isMobile(userName)) {
				ToastKit.showShort(this, "请输入您的手机号");
				userNameEditText.requestFocus();

			} else if (TextUtils.isEmpty(userName) || !RegexKit.isPassword(password)) {
				ToastKit.showShort(this, "请输入密码（6~20位）");
				passwordEditText.requestFocus();
			} else {
				final String uid = SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID);
				final String mid = SharedPreferencesKit.getString(this, Const.SP_KEY_USER_MID);
				Api.post("login", ApiParam.create().addParam("key", userName).addParam("pwd", AppKit.md5(password)), new ApiCallback(
						LoginActivity.this) {

					@Override
					public void handleSuccess(ApiResult result) {
						try {
							if (result.getCode() == 100) {

								SharedPreferencesKit.putString(getApplicationContext(), Const.SP_KEY_LAST_LOGIN_KEY, userName);
								SharedPreferencesKit.putString(getApplicationContext(), Const.SP_KEY_LAST_LOGIN_PWD, password);

								// 存储当前登录用户信息
								AppKit.storeUserInfo(getApplicationContext(), result.getData());

								// 链接融云
								AppKit.connectRongIM(getApplicationContext(), result.getData().getString("rtoken"));

								// Umeng push
								new Thread(new Runnable() {

									@Override
									public void run() {
										try {
											if (!TextUtils.isEmpty(uid)) {
												PushAgent.getInstance(getApplicationContext()).removeAlias(uid, "AID");
											}
											if (!TextUtils.isEmpty(mid)) {
												PushAgent.getInstance(getApplicationContext()).removeAlias(mid, "MID");
											}

											PushAgent.getInstance(getApplicationContext()).addAlias(
													SharedPreferencesKit.getString(getApplicationContext(), Const.SP_KEY_USER_ID), "AID");
											PushAgent.getInstance(getApplicationContext()).addAlias(
													SharedPreferencesKit.getString(getApplicationContext(), Const.SP_KEY_USER_MID), "MID");
										} catch (Exception e) {
											Log.e(TAG, e.getMessage(), e);
										}

									}
								}).start();

								getChannelData();
								// Intent mIntent = new
								// Intent(Const.FINISHLOGIN);
								// // 发送广播
								// sendBroadcast(mIntent);
							} else if (result.getStatus() == 0) {
								ToastKit.showLong(LoginActivity.this, "请求超时");
							} else {
								ToastKit.showLong(LoginActivity.this, "不存在的手机号或密码错误");
							}
						} catch (Exception e) {
							Log.e(TAG, e.getMessage(), e);
						}
						login.setClickable(true);
					}

					@Override
					public void handleFailure(Exception e, String msg) {
						ToastKit.showLong(LoginActivity.this, "手机号与密码信息不一致");
						login.setClickable(true);
					}
				}, LoginActivity.this);
			}
			login.setClickable(true);
			break;
		case R.id.infox_loginActivity_registerBtn:
			intent = new Intent(LoginActivity.this, RegisterActivity.class);
			startActivity(intent);
			break;
		case R.id.infox_loginactivity_frogectPsd:
			intent = new Intent(LoginActivity.this, FindPasswordActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}

	}

	/**
	 * 获取已登录会员频道数据
	 */
	private void getChannelData() {
		Api.get("me/info", ApiParam.create(), new ApiCallback(this, true) {

			@Override
			public void handleSuccess(ApiResult result) {

				try {
					ids = result.getData().getJSONArray("channel");
					
					SharedPreferencesKit.putJsonArray(getApplicationContext(), Const.TAGS,result.getData().getJSONArray("tags"));
					getAllChannelData();

				} catch (JSONException e) {
					Log.e(TAG, e.getMessage(), e);
				}
			}

			@Override
			public void handleFailure(Exception e, String msg) {
				finish();

			}
		}, this);

	}

	/**
	 * 获取所有频道数据
	 */
	private void getAllChannelData() {
		Api.data("channel_list.json", new ApiCallback(LoginActivity.this, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				ChannelManage.defaultUserChannels.clear();
				ChannelManage.defaultOtherChannels.clear();
				Const.unmove=0;
				int a = 0, b = 0;
				ArrayList<ChannelItem> list = new ArrayList<>();

				for (int i = 0; i < result.getDatas().length(); i++) {
					try {
						String id = result.getDatas().getJSONObject(i).getString("id");
						String title = result.getDatas().getJSONObject(i).getString("title");
						String type = result.getDatas().getJSONObject(i).getString("type");
						String cancel = result.getDatas().getJSONObject(i).getString("cancel");
						String sort = result.getDatas().getJSONObject(i).getString("sort");

						if (ids.length() == 0) {

							ChannelManage.defaultOtherChannels.add(new ChannelItem(id, title, b, 2, sort, type, cancel));
							System.out.println(b);
							b++;
						}

						for (int j = 0; j < ids.length(); j++) {

							if (id.equals(ids.get(j))) {
								if(cancel.equals("false")){
									Const.unmove++;
									
								}
								
								list.add(new ChannelItem(id, title, a, 1, sort, type, cancel));
								System.out.println(a);
								a++;
								break;
							} else {

								if (j == ids.length() - 1) {
									ChannelManage.defaultOtherChannels.add(new ChannelItem(id, title, b, 2, sort, type, cancel));
									System.out.println(b);
									b++;

								}
							}

						}

					} catch (JSONException e) {
						Log.e(TAG, e.getMessage(), e);
					}

				}

				for (int i = 0; i < ids.length(); i++) {
					for (int j = 0; j < list.size(); j++) {
						try {
							if (ids.get(i).equals(list.get(j).getId())) {
								ChannelManage.defaultUserChannels.add(list.get(j));

							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

				}

				// for (int j = 0; j < ids.length(); j++) {
				//
				// try {
				// for (int i = 0; i < result.getDatas().length(); i++) {
				// String id =
				// result.getDatas().getJSONObject(i).getString("id");
				// String title =
				// result.getDatas().getJSONObject(i).getString("title");
				// String type =
				// result.getDatas().getJSONObject(i).getString("type");
				// String cancel =
				// result.getDatas().getJSONObject(i).getString("cancel");
				// String sort =
				// result.getDatas().getJSONObject(i).getString("sort");
				//
				// if (ids.get(j).equals(id)) {
				//
				// ChannelManage.defaultUserChannels.add(new ChannelItem(id,
				// title, a, 1, sort, type, cancel));
				// a++;
				// } else {
				// if (j == ids.length() - 1) {
				// ChannelManage.defaultOtherChannels.add(new ChannelItem(id,
				// title, b, 2, sort, type, cancel));
				// b++;
				// }
				// }
				//
				// }
				// } catch (JSONException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }
				//
				// }
				// if (ids.length() == 0) {
				// for (int i = 0; i < result.getDatas().length(); i++) {
				//
				// try {
				// String id =
				// result.getDatas().getJSONObject(i).getString("id");
				// String title =
				// result.getDatas().getJSONObject(i).getString("title");
				// String type =
				// result.getDatas().getJSONObject(i).getString("type");
				// String cancel =
				// result.getDatas().getJSONObject(i).getString("cancel");
				// String sort =
				// result.getDatas().getJSONObject(i).getString("sort");
				// ChannelManage.defaultOtherChannels.add(new ChannelItem(id,
				// title, b, 2, sort, type, cancel));
				// b++;
				// } catch (JSONException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }
				// }
				//
				// }

				ChannelManage.getManage(Application.getInstance().getSQLHelper()).initDefaultChannel();
				Intent mIntent = new Intent(Const.DATACHANGE);
				// 发送广播
				sendBroadcast(mIntent);
				handler.sendEmptyMessage(0x666);
			}

			@Override
			public void handleFailure(Exception e, String msg) {

				finish();

			}
		}, LoginActivity.this);

	}
}
